package com.marisfrolg.storage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.CursorUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.IOUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.marisfrolg.base.BaseApplication;
import com.marisfrolg.entity.Check;
import com.marisfrolg.entity.Model;
import com.marisfrolg.entity.json.User;
import com.marisfrolg.util.ReadCodeController;
import com.marisfrolg.util.StringUtil;
import com.marisfrolg.util.WebServicesUtil;

public class CheckItemActivity extends ItemActivity {
//	@ViewInject(R.id.table)
//	private LinearLayout table;
	@ViewInject(R.id.addpanel)
	private RelativeLayout addpanel;
	@ViewInject(R.id.addcodenumber)
	private EditText addcodenumber;
	@ViewInject(R.id.checknum)
	private TextView checknum;
	@ViewInject(R.id.listView)
	private ListView listView;
//	private Map<String, RelativeLayout>rows=new HashMap<String, RelativeLayout>();
	private WebServicesUtil ws;
	private ProgressDialog progressDialog;
	private WSHandler handler;
	private int checkid;
	private ReadCodeController rcc;
	
	private static final int REFRESHITEM=22222;
//	private String xml="<?xml version=\"1.0\"?><ArrayOfItem xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Item><ProductNumber>A1113103501</ProductNumber><Quantity>22</Quantity></Item></ArrayOfItem>";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_check_item);
		ViewUtils.inject(this);
		handler=new WSHandler(this);
		ws=new WebServicesUtil(this,handler);
		sHandler=new ScanHandler(this);
		rcc=((BaseApplication)getApplication()).getReadCodeController();
		rcc.setHandler(sHandler);
		rcc.Open();
		Intent in = getIntent();
		checkid=in.getIntExtra("checkid", -1);
		checknum.setText("仓位:"+in.getStringExtra("checknum"));
//		List<Model> l=new ArrayList<Model>();
//		for(int i=0;i<3223;i++){
//			Model m=new Model();
//			m.checkid=checkid;
//			m.quantity=i;
//			m.setCodenumber("A33221X"+i);
//			m.setUpdatetime(new Date(System.currentTimeMillis()));
//			l.add(m);
//		}
//		try {
//			db.saveAll(l);
//		} catch (DbException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		if(checkid==-1||in.getStringExtra("checknum")==null){
			finish();
		}
		listView.setAdapter(new ListViewAdapter());
		refresh();
	}
//	@OnClick(R.id.getbinstock)
	public void getBinStock(){
		String bin="A2010102B";
		HashMap<String, Object>params=new HashMap<String, Object>();
		params.put("BIN", bin);
		Gson gson=new Gson();
		Type type = new TypeToken<User>() {}.getType();
		params.put("USER", gson.toJson(loginUser, type));
		progressDialog = ProgressDialog.show(this, "查询中", "请稍候...",true, false);
		ws.call(WebServicesUtil.ACTION_GETBINSTOCK, params, WebServicesUtil.URL_ACTION_GETBINSTOCK, WebServicesUtil.METHOD_ACTION_GETBINSTOCK);
	}
	@OnClick(R.id.listicon)
	public void add(View v){
		int visibility=addpanel.getVisibility();
		if(visibility!=View.VISIBLE){
			addpanel.setVisibility(View.VISIBLE);
		}else{
			addpanel.setVisibility(View.GONE);
			addcodenumber.setText("");
		}
	}
	@OnClick(R.id.addCheckItem)
	public void addCheckItem(View v){
		if(StringUtil.isEmpty(addcodenumber.getText()+"")){
			return;
		}
		new AlertDialog.Builder(this).setTitle("添加盘点款号").setMessage(("款号:"+addcodenumber.getText()).toUpperCase(new Locale("US"))).setPositiveButton("确定",new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Message msg=new Message();
				msg.what=ReadCodeController.CODEREAD;
				msg.obj=(addcodenumber.getText()+"").toUpperCase(new Locale("US"));
				rcc.getHandler().sendMessage(msg);
			}
		}).setNegativeButton("取消", null).show();
	}
	@SuppressLint("UseSparseArrays")
	@OnClick(R.id.submit)
	public void submit2(View v){
		List<Model> ms=null;
		try {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA);
			StringBuffer sb=new StringBuffer(" 导出时间(设备:"+loginUser.getImei()+")--"+sdf.format(new Date(System.currentTimeMillis()))+"\n\n仓位,款号,数量\n");
			List<Check> cs=db.findAll(Check.class);
			HashMap<Integer, String> csKey=new HashMap<Integer, String>();
			for (Check check : cs) {
				csKey.put(check.getId(), check.getCode());
			}
			ms=db.findAll(Selector.from(Model.class).orderBy("checkid"));
			int sum=0;
			for (Model model : ms) {
				sum+=model.quantity;
				sb.append(csKey.get(model.checkid));
				sb.append(",");
				sb.append(model.getCodenumber());
				sb.append(",");
				sb.append(model.quantity);
				sb.append("\n");
			}
			sb.replace(0, 1, "仓数:"+cs.size()+";款数:"+ms.size()+ ";总数量:"+sum+";  ");
			FileService fs=new FileService();
			try{
				fs.saveToSDCard("盘点.txt", sb.toString());
				new AlertDialog.Builder(this).setTitle("提示").setMessage("数据已生成.").setPositiveButton("确定", null).show();
			}catch(Exception e){
				new AlertDialog.Builder(this).setTitle("失败").setMessage("数据已生成失败,确认SD卡已挂载.").setPositiveButton("确定", null).show();
			}
		} catch (DbException e) {
			e.printStackTrace();
		}
	}
	
	public void submit(View v){
		Check c=null;
		List<Model> ms=null;
		try {
			c=db.findFirst(Selector.from(Check.class).where(WhereBuilder.b("id", "=", checkid)));
			ms=db.findAll(Selector.from(Model.class).where(WhereBuilder.b("checkid", "=", checkid)));
			if(c==null||ms.size()==0){
				new AlertDialog.Builder(this).setTitle("提示").setMessage("无数据").setPositiveButton("确定", null).show();
				return;
			}
			/**字符串 方式**/
			HashMap<String , Object> params=new HashMap<String, Object>();
			params.put("BIN", c.getCode());
			Gson gson=new Gson();
			Type type = new TypeToken<User>() {}.getType();
			params.put("USER", gson.toJson(loginUser, type));
			params.put("BINID", c.getId());
			params.put("ITEMS", StringUtil.getModelXml(ms));
			ws.call(WebServicesUtil.ACTION_UpdateBinActual2, params, WebServicesUtil.URL_ACTION_UpdateBinActual2, WebServicesUtil.METHOD_ACTION_UpdateBinActual2);
		} catch (DbException e) {
			e.printStackTrace();
		}
		/**Object 方式**/
//		WebServiceObject.Builder builder = new WebServiceObject.Builder(WebServicesUtil.URL, WebServicesUtil.NAMESPACE, WebServicesUtil.METHOD_ACTION_UpdateBinActual);
//		BinActualItemInfo[] bs=new BinActualItemInfo[1];
//		bs[0]=new BinActualItemInfo();
//		bs[0].setProperty(0, "A1113103501");
//		bs[0].setProperty(1, 33);
//		SoapObject go = builder.setStr("BIN", c.getCode()).setStr("USERNAME",un)
//				.setComplexList("ITEMS", "Item", Arrays.asList(bs))
//				.map(BinActualItemInfo.class)
//				.get().getSoapObject();
//		ws.callS(WebServicesUtil.ACTION_UpdateBinActual, go, WebServicesUtil.URL_ACTION_UpdateBinActual, WebServicesUtil.METHOD_ACTION_UpdateBinActual);
		
//		HashMap<String , Object> params=new HashMap<String, Object>();
//		params.put("BIN", c.getCode());
//		params.put("USERNAME", un);
//		Vector vector = new Vector(1);
//		BinActualItemInfo info = new BinActualItemInfo();
//		info.setProperty(0, "abc");
//		info.setProperty(1, 12);
//		
//		vector.add(info);
//		
//		params.put("ITEMS",vector );//StringUtil.getModelXml(ms)
//		ws.call(WebServicesUtil.ACTION_UpdateBinActual, params, WebServicesUtil.URL_ACTION_UpdateBinActual, WebServicesUtil.METHOD_ACTION_UpdateBinActual);
		
		progressDialog = ProgressDialog.show(CheckItemActivity.this, "查询中", "请稍候...", true, true);
		progressDialog.setCanceledOnTouchOutside(false);
		progressDialog.setOnCancelListener(new OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				WebServicesUtil.setConnectionTimeOut();
			}
		});
	}
	
	//动态加载
	private void refresh(){
		if(checkid!=-1){
			Cursor cursor=null;
			try {
				long amount=db.count(Selector.from(Model.class).where(WhereBuilder.b("checkid", "=", checkid)));
				cursor =db.execQuery("select sum(quantity) total from model where checkid="+checkid);
				if(cursor.moveToFirst()){
					long total= CursorUtils.getDbModel(cursor).getLong("total");
					TextView tvt=(TextView)findViewById(R.id.zongshu);
					tvt.setText(total+"");//更新总数
				}
				TextView tvk=(TextView)findViewById(R.id.kuanhaoshu);
				tvk.setText(amount+"");//更新款号数
				

				ListViewAdapter ba=(ListViewAdapter)listView.getAdapter();
				ba.SetCount((int)amount);
				ba.notifyDataSetChanged();
			} catch (DbException e) {
				e.printStackTrace();
			}finally{
				IOUtils.closeQuietly(cursor);
			}
			
		}
	}
	
	//全缓存模式
//	private void refreshbak(){
//		if(checkid!=-1){
//			table.removeAllViews();
//			try {
//				List<Model> models= db.findAll(Selector.from(Model.class).where(WhereBuilder.b("checkid", "=", checkid)).orderBy("updatetime", true));
//				int s=0;
//				if(models!=null){
//					for(Model m:models){
//						s++;
//						LayoutInflater inflater=LayoutInflater.from(this);
//						View v=inflater.inflate(R.layout.check_item, null);//直接从布局文件转化为view对象
//						TextView tvs=(TextView)v.findViewById(R.id.sequence);
//						String seq="#"+s;
//						tvs.setText(seq);
//						TextView tv=(TextView)v.findViewById(R.id.codenumber);
//						tv.setText(m.getCodenumber()+"");
//						TextView tvq=(TextView)v.findViewById(R.id.quantity);
//						tvq.setText(m.quantity+"");
//						View reduce=v.findViewById(R.id.reduce);
//						reduce.setOnClickListener(doReduce);
//						TextView tvid=(TextView)v.findViewById(R.id.modolid);
//						tvid.setText(m.getId()+"");
//						table.addView(v);
//						LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)v.getLayoutParams();
//						lp.topMargin=10;
//						lp.height=80;
//					}
//				}
//			} catch (DbException e) {
//				e.printStackTrace();
//			}
//		}
//		int total=0;
//		int amount=table.getChildCount();
//		for(int i=0;i<amount;i++){
//			RelativeLayout rl=(RelativeLayout)table.getChildAt(i);
//			TextView tvq=(TextView)rl.findViewById(R.id.quantity);
//			total+=Integer.valueOf(tvq.getText()+"");
//		}
//		TextView tvk=(TextView)findViewById(R.id.kuanhaoshu);
//		tvk.setText(amount+"");//更新款号数
//		TextView tvt=(TextView)findViewById(R.id.zongshu);
//		tvt.setText(total+"");//更新总数
//	}
	
	private static class WSHandler extends Handler {
		WeakReference<CheckItemActivity> wactivity;
		WSHandler(CheckItemActivity activity) {
			wactivity = new WeakReference<CheckItemActivity>(activity);
		}

		public void handleMessage(Message msg) {
			CheckItemActivity activity = wactivity.get();
			switch (msg.what) {
			case WebServicesUtil.ACTION_GETBINSTOCK:{
				Object a=msg.obj;
				System.out.println(a);
			}
			break;
			case WebServicesUtil.ACTION_UpdateBinActual2:{
				String result=msg.obj+"";
				if("0".equals(result)){
					Check c=null;
					try {
						c=activity.db.findFirst(Selector.from(Check.class).where(WhereBuilder.b("id", "=", activity.checkid)));
						if(c!=null){
							c.setUpdate(new Date(System.currentTimeMillis()));
							activity.db.update(c);
						}
					} catch (DbException e) {
						e.printStackTrace();
					}
					new AlertDialog.Builder(activity).setTitle("提示").setMessage("提交成功").setPositiveButton("确定", null).show();
				}else{
					new AlertDialog.Builder(activity).setTitle("提示").setMessage("提交失败-返回值:"+result).setPositiveButton("确定", null).show();
				}
				break;
			}
			case WebServicesUtil.TIMEOUT:{
				new AlertDialog.Builder(activity).setPositiveButton("确定", null).setTitle("提示").setMessage("连接超时").show();
				break;
			}
			case WebServicesUtil.NETUNREACHABLE:{
				Toast.makeText(activity, "网络无法连接或连接已取消,请稍后再试", Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
			activity.progressDialog.dismiss();
		}
	};
	//扫描处理类
	private static class ScanHandler extends Handler {
		WeakReference<CheckItemActivity> wactivity;
		ScanHandler(CheckItemActivity activity) {
			wactivity = new WeakReference<CheckItemActivity>(activity);
		}

		public void handleMessage(Message msg) {
			CheckItemActivity activity = wactivity.get();
			switch (msg.what) {
			case ReadCodeController.CODEREAD:{
				Model model=null;
				if(StringUtil.isBin(msg.obj+"")){
					Toast.makeText(activity, "输入的不是款号!", Toast.LENGTH_SHORT).show();
					activity.play_sound(false);
					return;
				}
				try {
					model=activity.db.findFirst(Selector.from(Model.class).where(WhereBuilder.b("codenumber", "=", msg.obj+"").and("checkid", "=", activity.checkid)));
					if(model!=null){
						model.quantity+=1;
						model.setUpdatetime(new Date(System.currentTimeMillis()));
						activity.db.update(model);
					}else{
						Model newModel=new Model();
						newModel.setCodenumber(msg.obj+"");
						newModel.checkid=activity.checkid;
						newModel.quantity=1;
						newModel.setUpdatetime(new Date(System.currentTimeMillis()));
						activity.db.saveBindingId(newModel);
					}
					activity.play_sound(true);
				} catch (DbException e) {
					e.printStackTrace();
				}
				activity.refresh();
				break;
			}
			case REFRESHITEM:
				try {
					Model m = activity.db.findNumberX(Selector.from(Model.class).where(WhereBuilder.b("checkid", "=", activity.checkid)).orderBy("updatetime", true),msg.arg1+1);
					
					for(int i=0;i<activity.listView.getChildCount();i++){
						View v=activity.listView.getChildAt(i);
						TextView tvs=(TextView)v.findViewById(R.id.sequence);
						if(("#"+(msg.arg1+1)).equals(tvs.getText()+"")){
							TextView tv=(TextView)v.findViewById(R.id.codenumber);
							tv.setText(m.getCodenumber()+"");//
							TextView tvq=(TextView)v.findViewById(R.id.quantity);
							tvq.setText(m.quantity+"");//
							View reduce=v.findViewById(R.id.reduce);
							reduce.setOnClickListener(activity.doReduce);
							TextView tvid=(TextView)v.findViewById(R.id.modolid);
							tvid.setText(m.getId()+"");//
						}
					}
					
				} catch (DbException e) {
					e.printStackTrace();
				}
				break;
			default:
				break;
			}
		}
	};
	
	private android.view.View.OnClickListener doReduce=new android.view.View.OnClickListener() {
		@Override
		public void onClick(View v) {
			final TextView id=(TextView)((RelativeLayout)v.getParent()).findViewById(R.id.modolid);
			TextView code=(TextView)((RelativeLayout)v.getParent()).findViewById(R.id.codenumber);
			AlertDialog.Builder alert=new AlertDialog.Builder(CheckItemActivity.this).setTitle("提示:").setNegativeButton("取消", null).setMessage("是否将:"+code.getText()+" 数量减少1").setPositiveButton("确定",new OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					Model model=null;
					try {
						model=db.findFirst(Selector.from(Model.class).where(WhereBuilder.b("id", "=", id.getText()+"")));
						if(model!=null){
							model.quantity-=1;
							if(model.quantity==0){
								db.delete(model);
							}else{
								db.update(model);
							}
						}
					}catch (DbException e){
						e.printStackTrace();
					}
					CheckItemActivity.this.refresh();
				}
			});
			alert.show();
		}
	};
	public void onBackPressed() {
		if(progressDialog!=null&&progressDialog.isShowing()){
			progressDialog.dismiss();
		}else{
			sHandler=null;
			finish();
		}
	};
	@Override
	protected void onStop() {
		super.onStop();
		sHandler=null;
		finish();
	}
	@Override
	protected void onPause() {
		sHandler=null;
		super.onPause();
		
	}
	protected void onResume() {
		super.onResume();
		refresh();
	};
	@Override
	protected void onDestroy() {
		super.onDestroy();
		sHandler=null;
		finish();
	}
	public void play_sound() {
		try {
			if (mediaPlayer == null)
				mediaPlayer = MediaPlayer.create(this, R.raw.noc);
			mediaPlayer.stop();
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	class ListViewAdapter extends BaseAdapter {  
        int count = 0;  
        public int getCount() {  
            return count;  
        }  
        public Object getItem(int position) {  
            return position;  
        }  
        public long getItemId(int position) {  
            return position;  
        }  
        public View getView(int position, View view, ViewGroup parent) {
//        	Model m;
			try {
//				m = db.findNumberX(Selector.from(Model.class).where(WhereBuilder.b("checkid", "=", checkid)).orderBy("updatetime", true),position+1);
				LayoutInflater inflater=LayoutInflater.from(CheckItemActivity.this);
				View v=inflater.inflate(R.layout.check_item, null);//直接从布局文件转化为view对象
				TextView tvs=(TextView)v.findViewById(R.id.sequence);
				String seq="#"+(1+position);
				tvs.setText(seq);
				TextView tv=(TextView)v.findViewById(R.id.codenumber);
				tv.setText("");//m.getCodenumber()+
				TextView tvq=(TextView)v.findViewById(R.id.quantity);
				tvq.setText("");//m.quantity+
				View reduce=v.findViewById(R.id.reduce);
				reduce.setOnClickListener(doReduce);
				TextView tvid=(TextView)v.findViewById(R.id.modolid);
				tvid.setText("");//m.getId()+
				Message msg=new Message();
				msg.what=REFRESHITEM;
				msg.arg1=position;
				sHandler.sendMessage(msg);
	            return v;  
			} catch (Exception e) {
				e.printStackTrace();
			}
			TextView mTextView;  
            if (view == null) {  
                mTextView = new TextView(CheckItemActivity.this);  
            } else {  
                mTextView = (TextView) view;  
            }  
            mTextView.setText("ERROR !!" + position);  
            mTextView.setTextSize(20f);  
            mTextView.setGravity(Gravity.CENTER);  
            mTextView.setHeight(90);  
            return mTextView;  
        }
        public void SetCount(int count){
        	this.count=count;
        }
    } 
	
	

	//临时
	 class FileService {

		public void saveToSDCard(String name, String content) {
			
			 FileOutputStream fos = null;
			 
			try{
				
				//Environment.getExternalStorageDirectory()。获取sd卡的路径


			File file = new File(Environment.getExternalStorageDirectory().getPath(),name);
			if(file.exists()){
				file.delete();
				
			}
			file.createNewFile();
		    fos = new FileOutputStream(file);
		    
		    fos.write(content.getBytes());
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	 }
}
